package com.yuandian.bpm.bi.modules.quartz.queue;

import com.yuandian.bpm.bi.modules.quartz.mapper.ConfReportFileInfoMapper;
import com.yuandian.bpm.bi.modules.quartz.mapper.ConfReportTaskLogMapper;
import com.yuandian.bpm.bi.modules.quartz.util.SpringContextJobUtil;
import com.yuandian.bpm.bi.modules.quartz.vo.ConfReportTaskLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;

/**
 * 异步保存日志信息
 */
@Slf4j
public class LogStorage implements Runnable {

	private static ConfReportTaskLogMapper logMapper;

    private final BlockingQueue<ConfReportTaskLog> logQueue;

    public LogStorage(BlockingQueue<ConfReportTaskLog> logQueue) { this.logQueue = logQueue; }


    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
				// 一部保存日志数据
				ConfReportTaskLog logContent = logQueue.take();
                saveLog(logContent);
            }
        } catch (InterruptedException e) {
            // 处理线程中断异常，可记录日志或执行其他操作
            Thread.currentThread().interrupt();
        }
    }



	/**
	 * 保存日志信息
	 * @param logContent	日志信息对象
	 */
    private void saveLog(ConfReportTaskLog logContent) {
		try {
			if (logMapper == null) {
				logMapper = (ConfReportTaskLogMapper) SpringContextJobUtil.getBean("confReportTaskLogMapper");
			}
			logMapper.saveLogInfo(logContent);
			log.info("[任务执行]-[任务id: {}]-保存日志信息", logContent.getTaskId());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("[任务执行]-[任务id: {}]-保存日志信息-报错", e.getMessage());
		}
    }
}
